
package vip.xiaonuo.biz.modular.lancerUsercoupon.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollStreamUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import vip.xiaonuo.auth.core.pojo.SaBaseLoginUser;
import vip.xiaonuo.auth.core.util.StpLoginUserUtil;
import vip.xiaonuo.biz.modular.lancerCoupon.entity.BizCoupon;
import vip.xiaonuo.biz.modular.lancerCoupon.service.BizCouponService;
import vip.xiaonuo.common.enums.CommonSortOrderEnum;
import vip.xiaonuo.common.exception.CommonException;
import vip.xiaonuo.common.page.CommonPageRequest;
import vip.xiaonuo.biz.modular.lancerUsercoupon.entity.BizUserCoupon;
import vip.xiaonuo.biz.modular.lancerUsercoupon.mapper.BizUserCouponMapper;
import vip.xiaonuo.biz.modular.lancerUsercoupon.param.BizUserCouponAddParam;
import vip.xiaonuo.biz.modular.lancerUsercoupon.param.BizUserCouponEditParam;
import vip.xiaonuo.biz.modular.lancerUsercoupon.param.BizUserCouponIdParam;
import vip.xiaonuo.biz.modular.lancerUsercoupon.param.BizUserCouponPageParam;
import vip.xiaonuo.biz.modular.lancerUsercoupon.service.BizUserCouponService;

import java.util.Date;
import java.util.List;

/**
 * C端优惠券Service接口实现类
 *
 * @author Lancer
 * @date  2024/03/15 11:48
 **/
@Service
public class BizUserCouponServiceImpl extends ServiceImpl<BizUserCouponMapper, BizUserCoupon> implements BizUserCouponService {


    @Autowired
    BizCouponService couponService;
    @Override
    public Page<BizUserCoupon> page(BizUserCouponPageParam bizUserCouponPageParam) {
        QueryWrapper<BizUserCoupon> queryWrapper = new QueryWrapper<>();
        if(ObjectUtil.isNotEmpty(bizUserCouponPageParam.getUserName())) {
            queryWrapper.lambda().like(BizUserCoupon::getUserName, bizUserCouponPageParam.getUserName());
        }
        if(ObjectUtil.isNotEmpty(bizUserCouponPageParam.getStartCreateTime()) && ObjectUtil.isNotEmpty(bizUserCouponPageParam.getEndCreateTime())) {
            queryWrapper.lambda().between(BizUserCoupon::getCreateTime, bizUserCouponPageParam.getStartCreateTime(), bizUserCouponPageParam.getEndCreateTime());
        }
        if(ObjectUtil.isAllNotEmpty(bizUserCouponPageParam.getSortField(), bizUserCouponPageParam.getSortOrder())) {
            CommonSortOrderEnum.validate(bizUserCouponPageParam.getSortOrder());
            queryWrapper.orderBy(true, bizUserCouponPageParam.getSortOrder().equals(CommonSortOrderEnum.ASC.getValue()),
                    StrUtil.toUnderlineCase(bizUserCouponPageParam.getSortField()));
        } else {
            queryWrapper.lambda().orderByAsc(BizUserCoupon::getId);
        }
        Page<BizUserCoupon> page = this.page(CommonPageRequest.defaultPage(), queryWrapper);
        List<BizUserCoupon> records = page.getRecords();
        for (BizUserCoupon record : records) {
            BizCoupon coupon = couponService.getById(record.getCouponId());
            // 填充优惠券详情
            record.setBrandName(coupon.getBrandName())
                    .setGoodsBoxName(coupon.getGoodsBoxName())
                    .setFullMoney(coupon.getFullMoney())
                    .setReductionMoney(coupon.getReductionMoney())
                    .setUseStartTime(coupon.getUseStartTime())
                    .setUseEndTime(coupon.getUseEndTime());
        }
        return page;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void add(BizUserCouponAddParam bizUserCouponAddParam) {
        BizUserCoupon bizUserCoupon = BeanUtil.toBean(bizUserCouponAddParam, BizUserCoupon.class);
        this.save(bizUserCoupon);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void edit(BizUserCouponEditParam bizUserCouponEditParam) {
        BizUserCoupon bizUserCoupon = this.queryEntity(bizUserCouponEditParam.getId());
        BeanUtil.copyProperties(bizUserCouponEditParam, bizUserCoupon);
        this.updateById(bizUserCoupon);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void delete(List<BizUserCouponIdParam> bizUserCouponIdParamList) {
        // 执行删除
        this.removeByIds(CollStreamUtil.toList(bizUserCouponIdParamList, BizUserCouponIdParam::getId));
    }

    @Override
    public BizUserCoupon detail(BizUserCouponIdParam bizUserCouponIdParam) {
        return this.queryEntity(bizUserCouponIdParam.getId());
    }

    @Override
    public BizUserCoupon queryEntity(String id) {
        BizUserCoupon bizUserCoupon = this.getById(id);
        if(ObjectUtil.isEmpty(bizUserCoupon)) {
            throw new CommonException("C端优惠券不存在，id值为：{}", id);
        }
        return bizUserCoupon;
    }

    @Override
    public void grabCoupon(String id) {
        SaBaseLoginUser loginUser = StpLoginUserUtil.getLoginUser();
        String id1 = loginUser.getId();
        // 判断是否获取过了优惠券
        LambdaQueryWrapper<BizUserCoupon> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper.eq(BizUserCoupon::getCouponId,id)
                .eq(BizUserCoupon::getUserId,id1);
        if (this.count(queryWrapper)>0){
            throw new CommonException("你已经领取过当前优惠券了！");
        }

        // 当前的优惠券
        BizCoupon coupon = couponService.getById(id);
        // 减少优惠券
        couponService.redCouponNumber(id,coupon.getCurrNumber());
        // 新增用户优惠券
        BizUserCoupon userCoupon = new BizUserCoupon();
        userCoupon.setCouponId(id)
                .setUserId(id1)
                .setUserName(loginUser.getName());
        this.save(userCoupon);
    }

    @Override
    public List<BizUserCoupon> getUserCouponListByUserId(String userId) {
        LambdaQueryWrapper<BizUserCoupon> queryWrapper=new LambdaQueryWrapper<>();
        queryWrapper
                .eq(BizUserCoupon::getUserId,userId);
        return this.list(queryWrapper);
    }


}
